package com.wjw.utils.office;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class OfficeUtils {
	
	private static final int WORD_HTML = 8;

	private static final int WORD_TXT = 7;

	private static final int EXCEL_HTML = 44;
	
	private static final int PPT_HTML = 12;
	
	// PpSaveAsFileType
	public static final int pptSaveAsJPG = 17;
	public static final int pptSaveAsHTML = 12;
	public static final int pptSaveAsHTMLv3 = 13;
	public static final int pptSaveAsHTMLDual = 14;
	public static final int pptSaveAsMetaFile = 15;
	public static final int pptSaveAsGIF = 16;
	public static final int pptSaveAsPNG = 18;
	public static final int pptSaveAsBMP = 19;
	public static final int pptSaveAsWebArchive = 20;
	public static final int pptSaveAsTIF = 21;
	public static final int pptSaveAsPresForReview = 22;
	public static final int pptSaveAsEMF = 23;
	public static final int pptSaveAsPDF = 32;// PDF
	private static final int EXCEL_XML = 46;
	

	/**
	 * 将word转换成html
	 * @param filename
	 * @param htmlFilename
	 */
	public static void wordToHtml(String filename, String htmlFilename) {
		ActiveXComponent xl = new ActiveXComponent("Word.Application");
		// 打开一个word，不显示窗口
		try {
			Dispatch.put(xl, "Visible", new Variant(false));
			Object workbooks = xl.getProperty("Documents").toDispatch();
			Object workbook = Dispatch.call((Dispatch) workbooks, "Open",
					filename).toDispatch();
			Dispatch.invoke((Dispatch) workbook, "SaveAs", Dispatch.Method,
					new Object[] { htmlFilename, new Variant(WORD_HTML) }, new int[1]);
			Variant f = new Variant(false);
			// Close关闭文件，不关闭窗口
			Dispatch.call((Dispatch) workbooks, "Close", f);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 调用office关闭方法，关闭窗口和word进程
			xl.invoke("Quit", new Variant[] {});
			xl = null;
		}
	}

	
	/**
	 * 将word转换成txt
	 * @param filename
	 * @param htmlFilename
	 */
	public static void wordToTxt(String filename, String htmlFilename) {
		ActiveXComponent xl = new ActiveXComponent("Word.Application");
		// 打开一个word，不显示窗口
		try {
			Dispatch.put(xl, "Visible", new Variant(false));
			Object workbooks = xl.getProperty("Documents").toDispatch();
			Object workbook = Dispatch.call((Dispatch) workbooks, "Open",
					filename).toDispatch();
			Dispatch.invoke((Dispatch) workbook, "SaveAs", Dispatch.Method,
					new Object[] { htmlFilename, new Variant(WORD_TXT) }, new int[1]);
			Variant f = new Variant(false);
			// Close关闭文件，不关闭窗口
			Dispatch.call((Dispatch) workbooks, "Close", f);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 调用office关闭方法，关闭窗口和word进程
			xl.invoke("Quit", new Variant[] {});
			xl = null;
		}
	}
	
	
	/**
	 * word转换为xml
	 * @param wordName word文件全路径
	 * @param xmlName xml文件全路径
	 */
	public static void wordToxml(String wordName,String xmlName){
        ComThread.InitSTA();
        ActiveXComponent   app   =   new   ActiveXComponent( "Word.Application");//启动word
        try   {
            app.setProperty( "Visible", new   Variant(false));//设置word不可见
            Dispatch docs   =   app.getProperty( "Documents").toDispatch();
            Dispatch doc   =   Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[]{wordName,new Variant(false), new Variant(true)}, new int[1]).toDispatch();//打开word文件
            Dispatch.invoke(doc, "SaveAs",   Dispatch.Method, new Object[]{xmlName,new   Variant(11)},   new   int[1]);//作为html格式保存到临时文件
            Variant   f   =   new   Variant(true);
            Dispatch.call((Dispatch)doc,   "Close",   f);
        }catch   (Exception   e)   {
            e.printStackTrace();
        }finally   {
            app.invoke( "Quit",   new   Variant[]   {});
        }
        ComThread.Release();
}
	
	/**
	 * 将excel转换成html
	 * @param filename
	 * @param htmlFilename
	 */
	public static void excelToHtml(String filename, String htmlFilename) {
	       ActiveXComponent xl = new ActiveXComponent("Excel.Application");
	       try {
	           Dispatch.put(xl, "Visible", new Variant(false));
	//打开一个Excel，不显示窗口
	           Object workbooks = xl.getProperty("workbooks").toDispatch();
	                        Object workbook = Dispatch.call((Dispatch) workbooks, "Open",
	                  filename).toDispatch();
	           Dispatch.invoke((Dispatch) workbook, "SaveAs", Dispatch.Method,
	                  new Object[] { htmlFilename, new Variant(EXCEL_HTML) }, new int[1]);
	           Dispatch.call((Dispatch) workbooks, "Close");
	       } catch (Exception e) {
	           e.printStackTrace();
	       } finally {
	           xl.invoke("Quit", new Variant[] {});
	           xl = null;
	           Process process;
	           int pid = 0;
	           try {
	              process = Runtime.getRuntime().exec("tasklist");
	              Scanner in = new Scanner(process.getInputStream());
	              while (in.hasNextLine()) {
	                  String p = in.nextLine();
	                  // 打印所有进程
	                  System.out.println(p);
	                  if (p.contains("EXCEL.EXE")) {
	                     StringBuffer buf = new StringBuffer();
	                     for (int i = 0; i < p.length(); i++) {
	                         char ch = p.charAt(i);
	                         if (ch != ' ') {
	                            buf.append(ch);
	                         }
	                     }
	                     // 打印pid，根据pid关闭进程
	                     System.out.println(buf.toString().split("Console")[0]
	                            .substring("EXCEL.EXE".length()));
	                     pid = Integer.parseInt(buf.toString().split("Console")[0]
	                            .substring("EXCEL.EXE".length()));
	                     Runtime.getRuntime().exec("tskill"+" "+pid);
	                  }
	              }
	           } catch (IOException e) {
	              e.printStackTrace();
	           }
	       }
	    }
	
	/**
	 * EXCEL转XML
	 * 
	 * @param xlsfile
	 *            EXCEL文件全路径
	 * @param xmlfile
	 *            转换后XML存放路径
	 */
	public static void excelToXml(String xlsfile, String xmlfile) {
		// 初始化
		ComThread.InitSTA();
		ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 启动Excel
		try {
			app.setProperty("Visible", new Variant(false));
			Dispatch excels = app.getProperty("Workbooks").toDispatch();
			Dispatch excel = Dispatch.invoke(
					excels,
					"Open",
					Dispatch.Method,
					new Object[] { xlsfile, new Variant(false),
							new Variant(true) }, new int[1]).toDispatch();
			Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {
					xmlfile, new Variant(EXCEL_XML) }, new int[1]);
			Variant f = new Variant(false);
			Dispatch.call(excel, "Close", f);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			app.invoke("Quit", new Variant[] {});
			ComThread.Release();
		}
	}

	/**
	 * word文件合并
	 * @param wordFileList word文件集合
	 * @param savepaths 合并后的word全路径名
	 */
	public static void uniteDoc(List wordFileList, String savepaths) {
		if (wordFileList.size() == 0 || wordFileList == null) {
			return;
		}
		// 打开word
		ActiveXComponent app = new ActiveXComponent("Word.Application");// 启动word
		try {
			// 设置word不可见
			app.setProperty("Visible", new Variant(false));
			// 获得documents对象
			Object docs = app.getProperty("Documents").toDispatch();
			// 打开第一个文件
			Object doc = Dispatch
					.invoke((Dispatch) docs,
							"Open",
							Dispatch.Method,
							new Object[] { (String) wordFileList.get(0),
									new Variant(false), new Variant(true) },
							new int[3]).toDispatch();
			// 追加文件
			for (int i = 1; i < wordFileList.size(); i++) {
				Dispatch.invoke(app.getProperty("Selection").toDispatch(),
						"insertFile", Dispatch.Method, new Object[] {
								(String) wordFileList.get(i), "",
								new Variant(false), new Variant(false),
								new Variant(false) }, new int[3]);
			}
			// 保存新的word文件
			Dispatch.invoke((Dispatch) doc, "SaveAs", Dispatch.Method,
					new Object[] { savepaths, new Variant(1) }, new int[3]);
			Variant f = new Variant(false);
			Dispatch.call((Dispatch) doc, "Close", f);
		} catch (Exception e) {
			throw new RuntimeException("合并word文件出错.原因:" + e);
		} finally {
			app.invoke("Quit", new Variant[] {});
		}
	}
	
	
	/**
     * PowerPoint转成HTML
     *
     * @param pptPath
     *            PowerPoint文件全路径
     * @param htmlfile
     *            转换后HTML存放路径
     */
    public static void pptToHtml(String pptPath, String htmlPath) {
       ActiveXComponent offCom = new ActiveXComponent("PowerPoint.Application");
       try {
           offCom.setProperty("Visible", new Variant(true));
           Dispatch excels = offCom.getProperty("Presentations").toDispatch();
           Dispatch excel = Dispatch.invoke(
                  excels,
                  "Open",
                  Dispatch.Method,
                  new Object[] { pptPath, new Variant(false),
                         new Variant(false) }, new int[1]).toDispatch();
           Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {
                  htmlPath, new Variant(PPT_HTML) }, new int[1]);
           Variant f = new Variant(false);
           Dispatch.call(excel, "Close");
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           offCom.invoke("Quit", new Variant[] {});
       }
    }
    
    /**
	 * 将ppt转换成图片及其它格式
	 * @param fileName
	 * @param saveTo
	 * @param pptSaveAsFileType
	 */
	public static void pptSaveAs(String fileName, String saveTo,int pptSaveAsFileType) {
		Dispatch pres = null;
		ActiveXComponent pptapp = null; // PowerPoint.Application
		Object ppto = null; // PowerPoint.Application COM Automation Object
		Object ppts = null; // Presentations Set
		try {
			pptapp = new ActiveXComponent("PowerPoint.Application");
			ppto = pptapp.getObject();
			ppts = Dispatch.get((Dispatch) ppto, "Presentations").toDispatch();

			pres = Dispatch.call((Dispatch) ppts, "Open", fileName,
					new Variant(-1), new Variant(-1),
					new Variant(0)).toDispatch();
			
			Dispatch.call(pres, "SaveAs", saveTo,
					new Variant(pptSaveAsFileType));
			
			if (pres != null) {
				Dispatch.call(pres, "Close");
			}
			if (pptapp != null) {
				try {
					pptapp.invoke("Quit", new Variant[] {});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	

	/**
	 * 将office(word excel ppt)转换成pdf
	 * @param officeFileName
	 * @param pdfFileName
	 */
	public static void officeToPdf(String officeFileName, String pdfFileName) {
		int officeSaveAsPDF = 0;
		File pdfFile=null;
		Dispatch officeDispatch=null;
		ActiveXComponent app = null;
		try {
			// word
			if (officeFileName.endsWith(".doc") || officeFileName.endsWith(".docx")) {
				app = new ActiveXComponent("Word.Application");
				officeSaveAsPDF = 17;
				app.setProperty("Visible", new Variant(false));
				officeDispatch = app.getProperty("Documents").toDispatch();
				// ppt
			} else if (officeFileName.endsWith(".ppt") || officeFileName.endsWith(".pptx")) {
				app = new ActiveXComponent("Powerpoint.Application");
				officeSaveAsPDF = 32;
				app.setProperty("Visible", new Variant(true));
				officeDispatch = app.getProperty("Presentations").toDispatch();
				// excel
			} else if (officeFileName.endsWith(".xls") || officeFileName.endsWith(".xlsx")) {
				app = new ActiveXComponent("Excel.Application");
				officeSaveAsPDF = 57;//
				app.setProperty("Visible", new Variant(false));
				officeDispatch = app.getProperty("Workbooks").toDispatch();
			} else {
				System.out.println("does not a office file......");
			}
			Dispatch doc = Dispatch.invoke(
					officeDispatch,
					"Open",
					Dispatch.Method,
					new Object[] { officeFileName, new Variant(false),
							new Variant(true) }, new int[1]).toDispatch();
			pdfFile = new File(pdfFileName);
			if (pdfFile.exists()) {
				pdfFile.delete();
			}
			Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
					pdfFileName, new Variant(officeSaveAsPDF) }, new int[1]);
			//
			if (officeFileName.endsWith(".ppt") || officeFileName.endsWith(".pptx")) {
				// do nothing
			} else {
				Variant f = new Variant(false);
				Dispatch.call(doc, "Close", f);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			app.invoke("Quit", new Variant[] {});
			try {
				Runtime.getRuntime().exec("taskkill /F /IM wordBook.exe")
						.waitFor();
				Runtime.getRuntime().exec("taskkill /F /IM excel.exe")
						.waitFor();
				Runtime.getRuntime().exec("taskkill /F /IM winword.exe")
						.waitFor();
				Runtime.getRuntime().exec("taskkill /F /IM powerpnt.exe")
						.waitFor();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

	public static void main(String[] args) {
//		excelToHtml("D:/b.xls","D:/aaa.html");
		//Office2Html.word2Html("C:\\Grails基础教程.doc", "C:\\test");
		//Office2Html.excel2Html("C:\\test.xls", "C:\\test");
		OfficeUtils.pptSaveAs("C:\\Users\\Administrator\\Desktop\\8反射.ppt","C:\\Users\\Administrator\\Desktop\\8反射.pdf",OfficeUtils.pptSaveAsPDF);
		//Office2Html.word2Txt("C:\\Grails基础教程.doc", "C:\\test");
	}
}
